//
//  BuddyListViewController.swift
//  XmppTry
//
//  Created by Arthur on 15/12/16.
//  Copyright © 2015年 Arthur. All rights reserved.
//

import UIKit

class BuddyListViewController: UITableViewController,StateDelegate,MessageDelegate{
    @IBAction func log(sender: UIBarButtonItem) {
        //根据当前在线状态，调整状态图片和进行上下线操作
        
        if logged {
            //下线
            logoff()
            //更改图片成离线
            sender.image = UIImage(named: "off")
            
        }else {
            //上线
            login()
            //更改图片成上线
            sender.image = UIImage(named: "on")
        }
        
        
        
    }
    
    @IBOutlet weak var mystates: UIBarButtonItem!
   
    //未读消息数组
    var unreadList=[WXMessage]()

    //好友状态数组，作为表格的数据源
    var stateList = [State]()
    
    
    //已登录
    var logged = false
    
    //选择的聊天的好友用户名
    var currentBuddyName = ""
    
    
    //自己离线
    func meOff() {
        //不用self
        logoff()
    }
    
    //收到离线或未读消息
    func newMsg(aMsg: WXMessage) {
        //如果消息有正文，则加入到未读消息组，通知表格刷新
        
        if (aMsg.body != "") {
            
            //则加入到围堵消息组
            unreadList.append(aMsg)
            //通知表格刷新
            self.tableView.reloadData()
        }
    }
    
    
    
    
    
    //好友上线状态处理(状态监听，加入状态数组，刷新表格－－－）
    
    func isOn(state: State) {
        //逐条查找
        for (index,oldstate) in EnumerateSequence(stateList) {                 //!!!!!!!!!
            //如果找到旧的用户状态
            if (state.name == oldstate.name) {
                
                //移除用户状态
                
                stateList.removeAtIndex(index)
                
                //一旦找到，就不找了，退出循环
                break
            }
            
            
        }
        
        //添加新状态到状态数组
        stateList.append(state)
        
        
        //刷新表格重载数据
        self.tableView.reloadData()
        
        
    }
    //好友下线状态处理
    func isOff(state: State) {
        //逐条查找
        for (index,oldstate) in EnumerateSequence(stateList) {                 //!!!!!!!!!
            //如果找到旧的用户状态
            if (state.name == oldstate.name) {
                
                //更改旧的用户状态，为上线
                
                stateList[index].isOnline = false
                //一旦找到，就不找了，退出循环
                break
            }
            
            
        }
        
        
        //刷新表格重载数据
        self.tableView.reloadData()
    }
    
    
    
    
    //获取总代理
    func appdelegate()  -> AppDelegate{
    
        return UIApplication.sharedApplication().delegate as! AppDelegate
    }
    
    //登入
    func login(){
        //清空数组
        unreadList.removeAll(keepCapacity: false)
        stateList.removeAll(keepCapacity: false)
        
        
        
        appdelegate().connect()
        
        //导航左边按钮图片改成上线图标
        mystates.image = UIImage(named: "on")
        
        logged = true
        
        //取用户名
        let myID = NSUserDefaults.standardUserDefaults().stringForKey("weixinID")
        
        
        //标题改成我的好友
        self.navigationItem.title = myID! + "的好友"
        
        self.tableView.reloadData()
    }
    
    
    
    //登出
    func logoff(){
        unreadList.removeAll(keepCapacity: false)
        stateList.removeAll(keepCapacity: false)
       
        appdelegate().disConnect()
        
        mystates.image = UIImage(named: "off")
        
        logged = false
        
    }
    
    
    
    
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
        
        
        
        
        
        //取用户名
        let myID = NSUserDefaults.standardUserDefaults().stringForKey("weixinID")
        
        //取自动登录
        let autologin = NSUserDefaults.standardUserDefaults().boolForKey("wxautologin")
        
        //如果配置了用户名和自懂登录，开始登录
        if(myID != nil && autologin  ){
            self.login()
            
            
            //其他情况，跳转到登录视图
        }else{
            self.performSegueWithIdentifier("toLoginSegue", sender: self)
        }
        
        //接管消息和状态代理
        appdelegate().statedelegate = self
       
        
        
        

        
        
    }
    
    
    
    override func viewDidAppear(animated: Bool) {
         appdelegate().messagedelegate = self
           }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    //
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return stateList.count
        
    }

    
    //单元格内容
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("buddyListCell", forIndexPath: indexPath)
        
        
        //好友状态
        let online = stateList[indexPath.row].isOnline
        
        
        //好友的名称
        let name = stateList[indexPath.row].name

        
        
        
        //未读消息的条数
        var unreads = 0
        //查找相应好友的未读条数
        for msg in unreadList {
            if(name == msg.from){
                
                unreads++
            }
        }
        
        
        
        
        
        //单元格文本 turtle
        cell.textLabel?.text = name + "(\(unreads))"
        
        if online {
            cell.imageView?.image = UIImage(named: "on")
        }else{
            cell.imageView?.image = UIImage(named: "off")
        }
        
        
        return cell
    }

    
    
    //选择单元格
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        //保存好友用户名
        currentBuddyName = stateList[indexPath.row].name
      
        //跳转到聊天时图
        
        self.performSegueWithIdentifier("toChatSegue", sender: self)
      
    }
    
    
    
    
    
    

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
        
        
        //是否转到聊天界面
        if (segue.identifier == "toChatSegue"){
            
            //取到聊天室图的控制器
            let dest = segue.destinationViewController as! ChatViewController
            
            //把当前选择单元格的用户名传递给聊天视图
            dest.toBuddyName =  currentBuddyName
            
            //把未读消息传递给聊天室图
            for msg in unreadList{
                
                if msg.from == currentBuddyName{
                    
                    //加入到聊天视图的消息组中
                    dest.msgList.append(msg)
                    
                }
                
            }
            //把相应的未读消息，从未读消息组中移除
            removeValueFromArray(currentBuddyName, aArray: &unreadList)
            
            
            //刷新表格，通知表格更新
            self.tableView.reloadData()
            
        }
        
        
        
        
    }

    
    @IBAction func UnwindToBList(segue: UIStoryboardSegue) {
        //如果是登录界面的完成按钮点击了，则开始登录
        let source = segue.sourceViewController as! LoginViewController
        
        if source.requireLogin {
            //注销前一个用户
            self.logoff()
            //登录xin用户
            self.login()
        }
        
       
    }


}
